﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

// This code has been adapted from the following source:
// http://forum.xda-developers.com/showpost.php?p=5627550&postcount=13
//
// Credit goes to: XdaDevelper Members: johncmolyneux, bgumble, RAMMANN and MichelDiamond

namespace SenseUtil
{
    public partial class SenseUtil : Form
    {
        #region constants
        static public class xTabAvilListData {
            public const int Name = 0;
            public const int Installed = Name + 1;
            public const int Author = Installed + 1;
            public const int Type = Author + 1;
            public const int KeyFile = Type + 1;
            public const int Url = KeyFile + 1;
            public const int UpdateUrl = Url + 1;
            public const int Present = UpdateUrl + 1;
            public const int Mode9 = Present + 1;
            public const int PageName = Mode9 + 1;
        }
        static public class xTabInstallListData
        {
            public const int PageName = 0;
            public const int Source = PageName+1;
            public const int MatchIndex = Source+1;
            public const int Mode9 = MatchIndex+1;
            public const int TCFileIndex = Mode9 + 1;
        }
        static public class xTabDetails {
            public const int Name = 0;
            public const int Author = Name + 1;
            public const int Url = Author + 1;
            public const int UpdateUrl = Url + 1;
            public const int Type = UpdateUrl + 1;
            public const int Mode9 = Type + 1;
            public const int PageName = Mode9 + 1;
        }
        static public class xTabData
        {
            public const int PageName = 0;
            public const int Mode9Ref = PageName + 1;
        }
        const string CSTR_SourceDefault = "Default";
        const string CSTR_SourceFile = "File";
        const string CSTR_GeneratedTabControlFile = "TabControl_manila";
        const string CSTR_TabInstalled = "Yes";
        const string CSTR_TabNotInstalled = "No";
        const string CSTR_TabPresent = "Present";
        const string CSTR_TabNotPresent = "Not Present";
        #endregion

        public SenseUtil()
        {
            InitializeComponent();
            SetListViewAvailableHeight();
            //Load the tab file data
            loadData();
        }

        public SenseUtil(string argument)
        {
            InitializeComponent();
            SetListViewAvailableHeight();
            //Load the tab file data
            loadData();

            //Options: renew or addall or addallnew
            if (String.Equals(argument, "renew"))
            {
                //Renew - set all tab control items to file source (if avilable)
                foreach (ListViewItem anItem in listViewTabControl.Items)
                {
                    //Check to see if the item can be switched or not
                    switchTabItemSource(anItem);
                }
                //Generate the tab control file & reset manila
                autorunFinish(argument);
            }
            else if (String.Equals(argument, "addall"))
            {
                //Add any tabs which are not installed but are present on the device
                addAllAvailabeAndNotInstalled();
                //Generate the tab control file & reset manila
                autorunFinish(argument);
            }
            else if (String.Equals(argument, "addallnew"))
            {
                //Add any tabs which are not installed but are present on the device
                addAllAvailabeAndNotInstalled();
                //Renew - set all tab control items to file source (if avilable)
                foreach (ListViewItem anItem in listViewTabControl.Items)
                {
                    //Check to see if the item can be switched or not
                    switchTabItemSource(anItem);
                }
                //Generate the tab control file & reset manila
                autorunFinish(argument);
            }
        }

        public SenseUtil(string argument, string filename)
        {
            InitializeComponent();
            SetListViewAvailableHeight();
            //Load the tab file data
            loadData();

            //Check file exists
            filename = filename.Replace(TabList.CSTR_FileExt, ""); //Remove .xml ext if present, so we can add it every time
            string fullfilename = Settings.GetApplicationPathOnly() + TabList.CSTR_ResourcePath + filename + TabList.CSTR_FileExt;
            if (File.Exists(fullfilename))
            {
                //Find the filename in the available list
                foreach (ListViewItem anItem in listViewAvailable.Items)
                {
                    //look for the matching key file
                    if (string.Equals(anItem.SubItems[xTabAvilListData.KeyFile].Text, filename,StringComparison.OrdinalIgnoreCase))
                    {
                        //If the command is ADD
                        if (String.Equals(argument, "add"))
                        {
                            //Check is present and not installed
                            if (!isItemAvaiableAndNotInstalled(anItem))
                            {
                                MessageBox.Show("KeyFile Missing OR Item Already Installed: " + filename);
                            }
                            else
                            {
                                //add the file to last but one position (before settings page)
                                //int targetIndex = 0;
                                //if (listViewTabControl.Items.Count - 1 >= 0)
                                //{
                                //    targetIndex = listViewTabControl.Items.Count - 1;
                                //}

                                //add the file to tab after the home tab (position 1)
                                int targetIndex = 0;
                                if (listViewTabControl.Items.Count >= 1)
                                {
                                    targetIndex = 1;
                                }

                                int sourceIndex = anItem.Index;
                                addTabToTabControlList(sourceIndex, targetIndex);

                                //Disable the add button
                                buttonItemAdd.Enabled = false;

                                //Generate the tab control file & reset manila
                                autorunFinish(argument + " with " + filename);

                                break;
                            }
                        }
                        //If command is REMOVE
                        else if (String.Equals(argument, "remove"))
                        {
                            if(anItem.SubItems[xTabAvilListData.Installed].Text == CSTR_TabInstalled)
                            {
                                //Update the available tabs list, to set as not installed anymore
                                anItem.SubItems[xTabAvilListData.Installed].Text = CSTR_TabNotInstalled;
                                //Find matching item in tab control list
                                foreach (ListViewItem theItem in listViewTabControl.Items)
                                {
                                    if (theItem.SubItems[xTabInstallListData.MatchIndex].Text == anItem.Index.ToString())
                                    {
                                        //Remove the current item from the list
                                        listViewTabControl.Items.Remove(theItem);

                                        //Generate the tab control file & reset manila
                                        autorunFinish(argument + " with " + filename);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Resource File Missing: " + filename);
                //Close!
                Close();
            }
        }

        #region Initialisation
        #region Initialisation - Layout
        private void SetListViewAvailableHeight()
        {
            int size = this.Size.Height - this.Top;

            //Tab (Installed)
            this.buttonItemUp.Location = new Point(this.buttonItemUp.Location.X, size - this.buttonItemUp.Size.Height);
            this.buttonItemSource.Location = new Point(this.buttonItemSource.Location.X, size - this.buttonItemUp.Size.Height);
            this.buttonItemRemove.Location = new Point(this.buttonItemRemove.Location.X, size - this.buttonItemUp.Size.Height);
            this.buttonItemDown.Location = new Point(this.buttonItemDown.Location.X, this.buttonItemUp.Location.Y);
            this.buttonBuild.Location = new Point(this.buttonBuild.Location.X, this.buttonItemUp.Location.Y);
            listViewTabControl.Size = new System.Drawing.Size(this.Size.Width, size - (size - this.buttonItemUp.Location.Y + 6));

            //Tab (Available)
            this.labelDetailsPresent.Location = new Point(6, size - (this.labelDetailsPresent.Size.Height + this.linkDetailsUrl.Size.Height + this.linkDetailsUpdateUrl.Size.Height));
            this.buttonItemAddAll.Location = new Point((this.Size.Width - this.buttonItemAddAll.Size.Width) - 6, size - (this.buttonItemAddAll.Size.Height + this.linkDetailsUrl.Size.Height + this.linkDetailsUpdateUrl.Size.Height));
            this.buttonItemAdd.Location = new Point(((this.Size.Width - this.buttonItemAddAll.Size.Width)- this.buttonItemAdd.Size.Width) - 12, size - (this.buttonItemAdd.Size.Height + this.linkDetailsUrl.Size.Height + this.linkDetailsUpdateUrl.Size.Height));
            this.linkDetailsUrl.Location = new Point(6, size - (this.linkDetailsUrl.Size.Height + this.linkDetailsUpdateUrl.Size.Height));
            this.linkDetailsUpdateUrl.Location = new Point(6, size - (this.linkDetailsUpdateUrl.Size.Height));
            listViewAvailable.Size = new System.Drawing.Size(this.Size.Width, size - (size - this.labelDetailsPresent.Location.Y));

            linkDetailsUrl.Text = "";
            linkDetailsUpdateUrl.Text = "";
            labelDetailsPresent.Text = "";
        }
        #endregion
        private void InitialiseControls()
        {
            buttonStart.Enabled = !SenseControl.isSenseRunning();
            buttonStop.Enabled = SenseControl.isSenseRunning();
            buttonRestart.Enabled = SenseControl.isSenseRunning();
            buttonReset.Enabled = SenseControl.isManilaFullPresent();
            buttonFullReset.Enabled = SenseControl.isConfigKeyPresent();
            buttonTCFUpdate.Enabled = TabFileBuilder.isGeneratedFilePresent(Settings.GetApplicationPathOnly() + CSTR_GeneratedTabControlFile + TabList.CSTR_FileExt);
            buttonItemAddAll.Enabled = isAnyItemsAvailableAndNotInstalledTrue();
        }
        private void InitialiseTabLists()
        {
            listViewAvailable.View = View.Details;
            //  listViewAvailable.CheckBoxes = true;
            listViewAvailable.FullRowSelect = true;
            //Ensure control is fully cleared
            listViewAvailable.Clear();

            string[] avilableTabs = TabList.ListAvailableTabs();
            //Ensure tab files were found
            if ((avilableTabs != null) && (avilableTabs.Length > 0))
            {
                //For each tab file populate the list view data
                for (int i = 0; i < avilableTabs.Length; i++)
                {
                    //Add data to listview
                    string[] details = TabList.FetchXmlDetails(avilableTabs[i]);
                    ListViewItem tabfile = new ListViewItem(details[xTabDetails.Name]);
                    tabfile.SubItems.Add(CSTR_TabNotInstalled); //Set null installed value (will be reset when tab control file loaded
                    tabfile.SubItems.Add(details[xTabDetails.Author]);
                    tabfile.SubItems.Add(details[xTabDetails.Type]);
                    tabfile.SubItems.Add(avilableTabs[i]);
                    tabfile.SubItems.Add(details[xTabDetails.Url]);
                    tabfile.SubItems.Add(details[xTabDetails.UpdateUrl]);
                    if (TabList.CheckFilePresent(avilableTabs[i]))
                    {
                        tabfile.SubItems.Add(CSTR_TabPresent);
                    }
                    else
                    {
                        tabfile.SubItems.Add(CSTR_TabNotPresent);
                    }
                    tabfile.SubItems.Add(details[xTabDetails.Mode9]);
                    tabfile.SubItems.Add(details[xTabDetails.PageName]);
                    listViewAvailable.Items.Add(tabfile);
                }
                //Populate the coloumns
                AddlistViewAvailableColumns();
            }


        }
        private void InitialiseTabControl()
        {
            listViewTabControl.View = View.Details;
            //  listViewTabControl.CheckBoxes = true;
            listViewTabControl.FullRowSelect = true;
            //Ensure control is fully cleared
            listViewTabControl.Clear();

            List <string[]> installedTabs = TabControlFile.TabControlDetails();
            if (installedTabs.Count > 0)
            {
                int fileindex=0;//track the index
                foreach (string[] tab in installedTabs)
                {
                    ListViewItem tabitem = new ListViewItem(tab[xTabData.PageName]);
                    tabitem.SubItems.Add(CSTR_SourceDefault);//Add default source i.e. generate from original tab control file
                    //Find matching available tab index
                    int matchIndex = FindMatchingTabIndex(tab[xTabData.Mode9Ref]);
                    tabitem.SubItems.Add(matchIndex.ToString());
                    tabitem.SubItems.Add(tab[xTabData.Mode9Ref]);
                    tabitem.SubItems.Add(fileindex.ToString());
                    listViewTabControl.Items.Add(tabitem);
                    fileindex++;
                }
                //Populate the coloumns
                AddlistViewTabControlColumns();
            }
        }
        #endregion

        #region Event Handlers
        #region Sense Control Events
        private void buttonRestart_Click(object sender, EventArgs e)
        {
            buttonStart.Enabled = false; //Set to indicate change!
            buttonStop.Enabled = false; //Set to indicate change!
            buttonRestart.Enabled = false; //Set to indicate change!
            SenseControl.RestartManila();
            InitialiseControls();
        }
        private void buttonStart_Click(object sender, EventArgs e)
        {
            SenseControl.StartManila();
            InitialiseControls();
        }
        private void buttonStop_Click(object sender, EventArgs e)
        {
            SenseControl.StopManila();
            InitialiseControls();
        }
        private void buttonReset_Click(object sender, EventArgs e)
        {
            SenseControl.ResetManila();
            InitialiseControls();
        }
        private void buttonFullReset_Click(object sender, EventArgs e)
        {
            SenseControl.FullResetManila();
            InitialiseControls();
        }
        private void buttonSoftReset_Click(object sender, EventArgs e)
        {
            //Check before doing this...
            if (MessageBox.Show("Perform soft-reset - device will be restarted, any unsaved data will be lost.", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                SenseControl.ResetPocketPC();
                InitialiseControls();
            }
        }
        private void buttonBuild_Click(object sender, EventArgs e)
        {
            //Generate the tab control file
            string generatedFile = buildTabControlFile();

            //If file is valid open?
            if (generatedFile != "")
            {
                if (MessageBox.Show("File Completed - Open?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    try
                    {
                        if (File.Exists(TabList.CSTR_WindowsPath + "notepadPPC.exe"))
                        {
                            System.Diagnostics.Process.Start(TabList.CSTR_WindowsPath + "notepadPPC.exe", generatedFile);
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(generatedFile, "");
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Unable to display file");
                    }
                }
                //Enable the update button
                buttonTCFUpdate.Enabled = true;
            }
            else
            {
                MessageBox.Show("Unable to generate file");
            }
        }
        private void buttonTCFUpdate_Click(object sender, EventArgs e)
        {
            //update the tab control file
            updateTabControlFile();

            //Re-initialse the controls
            InitialiseControls();

            //Reload all the data
            loadData();

            MessageBox.Show("The tab control file has been replaced and sense restarted.  Note: If sense does not start, try a softreset.");
        }
        #endregion

        #region List View Installed Handlers
        private void listViewTabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Ensure at least one item is selected
            if (listViewTabControl.SelectedIndices.Count != 0)
            {
                //Enable buttons
                buttonItemSource.Enabled = isSourceAvailable(listViewTabControl.SelectedIndices[0]);
                buttonItemRemove.Enabled = true;
                //Only if not at the top
                if (listViewTabControl.SelectedIndices[0] == 0)
                {
                    buttonItemUp.Enabled = false;
                }
                else
                {
                    buttonItemUp.Enabled = true;
                }
                //Only if not at the bottom
                int lastItem = listViewTabControl.SelectedIndices.Count - 1;
                if (listViewTabControl.SelectedIndices[lastItem] == (listViewTabControl.Items.Count - 1))
                {
                    buttonItemDown.Enabled = false;
                }
                else
                {
                    buttonItemDown.Enabled = true;
                }
            }
            else
            {
                //Disable buttons
                buttonItemSource.Enabled = false;
                buttonItemRemove.Enabled = false;
                buttonItemUp.Enabled = false;
                buttonItemDown.Enabled = false;
            }

        }
        private void buttonItemUp_Click(object sender, EventArgs e)
        {
            //Ensure at least one item is selected
            if (listViewTabControl.SelectedIndices.Count != 0)
            {
                foreach (int index in listViewTabControl.SelectedIndices)
                {
                    //Ensure we are not at the top
                    if (index > 0)
                    {
                        ListViewItem theItem = (ListViewItem)listViewTabControl.Items[index].Clone();
                        //Unselect Item
                        listViewTabControl.Items[index].Selected = false;
                        //Delete the old item
                        listViewTabControl.Items.RemoveAt(index);
                        //Copy the selected item up one in the list (if not at the top)
                        listViewTabControl.Items.Insert(index - 1, theItem);
                        //Select the item
                        listViewTabControl.Items[index - 1].Selected = true;
                    }
                }
                listViewTabControl.Refresh();
            }
        }
        private void buttonItemDown_Click(object sender, EventArgs e)
        {
            //Ensure at least one item is selected
            if (listViewTabControl.SelectedIndices.Count != 0)
            {
                foreach (int index in listViewTabControl.SelectedIndices)
                {
                    //Ensure we are not at the bottom
                    if (index < (listViewTabControl.Items.Count - 1))
                    {
                        ListViewItem theItem = (ListViewItem)listViewTabControl.Items[index].Clone();
                        //Unselect Item
                        listViewTabControl.Items[index].Selected = false;
                        //Delete the old item
                        listViewTabControl.Items.RemoveAt(index);
                        //Copy the selected item up one in the list (if not at the top)
                        listViewTabControl.Items.Insert(index + 1, theItem);
                        //Select the item
                        listViewTabControl.Items[index+1].Selected = true;
                    }
                }
                listViewTabControl.Refresh();
            }
        }
        private void buttonItemSource_Click(object sender, EventArgs e)
        {
            //Ensure at least one item is selected
            if (listViewTabControl.SelectedIndices.Count != 0)
            {
                foreach (int index in listViewTabControl.SelectedIndices)
                {
                    //Toggle between Default and file (if file exists)
                    ListViewItem theItem = listViewTabControl.Items[index];
                    //Check to see if the item can be switched or not
                    switchTabItemSource(theItem);
                }
            }
        }
        private void buttonItemRemove_Click(object sender, EventArgs e)
        {
            //Ensure at least one item is selected
            if (listViewTabControl.SelectedIndices.Count != 0)
            {
                foreach (int index in listViewTabControl.SelectedIndices)
                {
                    //Update the available tabs list, to set as not installed anymore
                    int matchIndex = Convert.ToInt16(listViewTabControl.Items[index].SubItems[xTabInstallListData.MatchIndex].Text);
                    listViewAvailable.Items[matchIndex].SubItems[xTabAvilListData.Installed].Text = CSTR_TabNotInstalled;
                    //Delete the item
                    listViewTabControl.Items.RemoveAt(index);
                    //Select the next item
                    if (index < listViewTabControl.Items.Count)
                    {
                        listViewTabControl.Items[index].Selected = true;
                    }
                    else
                    {
                        //Ensure we are not at the top
                        if (index > 0)
                        {
                            listViewTabControl.Items[index - 1].Selected = true;
                        }
                    }
                }
            }
        }
        #endregion

        #region List View Avilable Handlers
        private void listViewAvailable_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Check if item is selected
            if (listViewAvailable.FocusedItem != null)
            {
                //Populate the details data in the display
                string value;
                ListViewItem theItem = listViewAvailable.FocusedItem;
                value = theItem.SubItems[xTabAvilListData.Url].Text;
                if ((value != null) && (value != ""))
                {
                    linkDetailsUrl.Text = "Details Link";
                    linkDetailsUrl.Tag = value;
                }
                else
                {
                    linkDetailsUrl.Text = "";
                    linkDetailsUrl.Tag = "";
                }
                value = theItem.SubItems[xTabAvilListData.UpdateUrl].Text;
                if ((value != null) && (value != ""))
                {
                    linkDetailsUpdateUrl.Text = "Update Link";
                    linkDetailsUpdateUrl.Tag = value;
                }
                else
                {
                    linkDetailsUpdateUrl.Text = "";
                    linkDetailsUpdateUrl.Tag = "";
                }
                value = theItem.SubItems[xTabAvilListData.Present].Text;
                if ((value != null) && (value != ""))
                {
                    labelDetailsPresent.Text = value + " On Device";
                }
                else
                {
                    labelDetailsPresent.Text = "";
                }

                //Enable the add button (if not installed)
                if (theItem.SubItems[xTabAvilListData.Installed].Text == CSTR_TabNotInstalled)
                {
                    buttonItemAdd.Enabled = true;
                }
                else
                {
                    buttonItemAdd.Enabled = false;
                }
            }
            else
            {
                //Disable the add button
                buttonItemAdd.Enabled = false;
            }

        }
        private void linkDetailsUrl_Click(object sender, EventArgs e)
        {
            //Open up the link related to the label
            System.Diagnostics.Process.Start(linkDetailsUrl.Tag.ToString(), null);
        }
        private void linkDetailsUpdateUrl_Click(object sender, EventArgs e)
        {
            //Open up the link related to the label
            System.Diagnostics.Process.Start(linkDetailsUpdateUrl.Tag.ToString(), null);
        }
        private void buttonItemAdd_Click(object sender, EventArgs e)
        {
            //Check current focused item is not alread installed
            if (listViewAvailable.FocusedItem.SubItems[xTabAvilListData.Installed].Text == CSTR_TabNotInstalled)
            {
                //If tab is not detected on the device, warn the user!
                if (listViewAvailable.FocusedItem.SubItems[xTabAvilListData.Present].Text == CSTR_TabNotPresent)
                {
                    if (MessageBox.Show("Tab was not detected on the device, sense will not start, continue anyway?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    {
                        return; //Do not add the tab
                    }
                }

                //We can now add the tab to the Tab Control File's List
                int targetIndex = 0;
                //See if an item is selected in the Tab Control File list
                if(listViewTabControl.FocusedItem != null)
                {
                    //Insert at the selected location
                    targetIndex = listViewTabControl.FocusedItem.Index;
                }
                else
                {
                    //add the file to last but one position (before settings page)
                    if (listViewTabControl.Items.Count - 1 >= 0)
                    {
                        targetIndex = listViewTabControl.Items.Count - 1;
                    }
                }
                int sourceIndex = listViewAvailable.FocusedItem.Index;
                addTabToTabControlList(sourceIndex, targetIndex);

                //Disable the add button
                buttonItemAdd.Enabled = false;

            }
        }
        private void buttonItemAddAll_Click(object sender, EventArgs e)
        {
            //Add any tabs which are not installed but are present on the device
            addAllAvailabeAndNotInstalled();
        }
        #endregion

        #region Settings Event Handlers
        private void buttonRegLSoftkey_Click(object sender, EventArgs e)
        {
            Settings.SetSoftKey(1, "Sense Util", Settings.GetApplicationFullPath(), true);
        }
        private void buttonRegRSoftkey_Click(object sender, EventArgs e)
        {
            Settings.SetSoftKey(2, "Sense Util", Settings.GetApplicationFullPath(), true);
        }
        private void buttonRegDefaultSoftKey_Click(object sender, EventArgs e)
        {
            Settings.SetSoftKey(0, "", "", true);
        }
        private void buttonReloadData_Click(object sender, EventArgs e)
        {
            //Prompt because edits will be lost
            if (MessageBox.Show("Reload Available Tabs & Control File? Note all changes/edits will be lost.", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                loadData();
            }
        }
        private void checkBoxAdvanced_CheckStateChanged(object sender, EventArgs e)
        {
            //Change the colums being displayed
            AddlistViewTabControlColumns();
            AddlistViewAvailableColumns();
        }
        #endregion
        #endregion


        #region private functions
        private void replaceTabControlFile()
        {
            string local_path = Settings.GetApplicationPathOnly();
            string file_generated = local_path + CSTR_GeneratedTabControlFile + TabList.CSTR_FileExt;
            string file_original = TabControlFile.CSTR_WindowsPath + TabControlFile.CSTR_TabControlFilename;
            try
            {
                //Check for generated file, backup the old one and replace
                if (File.Exists(file_generated))
                {
                    //File already present make a backup
                    if (File.Exists(file_original))
                    {
                        string datetime = DateTime.Now.ToShortDateString().Replace("/","");
                        datetime += DateTime.Now.ToLongTimeString().Replace(":", "");
                        string file_backup = local_path + TabControlFile.CSTR_TabControlFilename + datetime + TabList.CSTR_FileExt;
                        try
                        {
                            File.Copy(file_original, file_backup, true);
                        }
                        catch
                        {
                            MessageBox.Show("Backup File NOT created! " + file_backup);
                        }
                        //Check backup file has been made
                        if (File.Exists(file_backup))
                        {
                            //Attempt to replace the original file
                            try
                            {
                                File.Copy(file_generated, file_original, true);
                            }
                            catch
                            {
                                MessageBox.Show("Unable to replace Original Tab Control file! " + file_original);
                            }
                        }


                    }


                }
            }
            catch
            {
                MessageBox.Show("Unable to update file");
            }
        }
        private int FindMatchingTabIndex(string reference)
        {
            int index = 99;

            //For each item in the available tab list, see if the mode9 reference is present in the reference
            foreach (ListViewItem anItem in listViewAvailable.Items)
            {
                //See if the mode9 avilable reference is within the reference provided
                if (reference.Contains(anItem.SubItems[xTabAvilListData.Mode9].Text))
                {
                    index = anItem.Index;
                    anItem.SubItems[xTabAvilListData.Installed].Text = CSTR_TabInstalled;
                    break;
                }
            }

            return index;
        }
        private void AddlistViewTabControlColumns()
        {
            //Clear any colums if they exist and generate new ones
            listViewTabControl.Columns.Clear();
            //Depending on the advanced view mode to if we display normal column view or all
            if (checkBoxAdvanced.Checked)
            {
                //Populate all the coloumns
                listViewTabControl.Columns.Add("PageName", 250, HorizontalAlignment.Left);
                listViewTabControl.Columns.Add("Source", 130, HorizontalAlignment.Left);
                listViewTabControl.Columns.Add("MatchIndex", 150, HorizontalAlignment.Left);
                listViewTabControl.Columns.Add("Mode9", 400, HorizontalAlignment.Left);
                listViewTabControl.Columns.Add("FileIndex", 150, HorizontalAlignment.Left);
            }
            else
            {
                //Populate the important ones
                listViewTabControl.Columns.Add("PageName", 250, HorizontalAlignment.Left);
                listViewTabControl.Columns.Add("Source", 130, HorizontalAlignment.Left);
            }
            listViewTabControl.Refresh();
        }
        private void AddlistViewAvailableColumns()
        {
            //Clear any colums if they exist and generate new ones
            listViewAvailable.Columns.Clear();
            //Depending on the advanced view mode to if we display normal column view or all
            if (checkBoxAdvanced.Checked)
            {
                //Populate all the coloumns
                listViewAvailable.Columns.Add("Name", 200, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Installed", 100, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Author", 170, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Type", 150, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("KeyFile", 250, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Url", 300, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("UpdateUrl", 300, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Present", 150, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Mode9", 400, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("PageName", 250, HorizontalAlignment.Left);
            }
            else
            {
                //Populate the important ones
                listViewAvailable.Columns.Add("Name", 200, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Installed", 100, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Author", 170, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("Type", 150, HorizontalAlignment.Left);
                listViewAvailable.Columns.Add("KeyFile", 250, HorizontalAlignment.Left);
            }
            listViewAvailable.Refresh();
        }
        private void addTabToTabControlList(int sourceIndex, int targetIndex)
        {
            //Get tab being refered to from the available tab list
            ListViewItem sourceTab = listViewAvailable.Items[sourceIndex];

            //Create a new tab item for the control list
            ListViewItem tabitem = new ListViewItem(sourceTab.SubItems[xTabAvilListData.PageName].Text);
            tabitem.SubItems.Add(CSTR_SourceFile);//Add file source i.e. generate from xml tab control file
            tabitem.SubItems.Add(sourceIndex.ToString());//Set to the source index
            tabitem.SubItems.Add(sourceTab.SubItems[xTabAvilListData.Mode9].Text);
            tabitem.SubItems.Add("99");
            listViewTabControl.Items.Insert(targetIndex,tabitem);
            //Set the source tab to installed
            sourceTab.SubItems[xTabAvilListData.Installed].Text = CSTR_TabInstalled;

        }
        private bool isSourceAvailable(int index)
        {
            bool available = false;
            //Check to see if source can be toggled
            ListViewItem theItem = listViewTabControl.Items[index];
            //If the tab was set to default
            if (theItem.SubItems[xTabInstallListData.Source].Text == CSTR_SourceDefault)
            {
                //check for valid file (not MatchIndex 99)
                if (theItem.SubItems[xTabInstallListData.MatchIndex].Text != "99")
                {
                    available = true;
                }
            }
            else//If the tab was set to file
            {
                //Check tab was in Tab Control file
                if (theItem.SubItems[xTabInstallListData.TCFileIndex].Text != "99")
                {
                    available = true;
                }
            }

            return available;
        }
        private bool isAnyItemsAvailableAndNotInstalledTrue()
        {
            //Check the list and determine if there are any which are present but not installed
            bool Present = false;

            foreach (ListViewItem anItem in listViewAvailable.Items)
            {
                //Check to see if NOT installed but present
                Present = isItemAvaiableAndNotInstalled(anItem);
                if (Present)
                {
                    break;
                }
            }
            return Present;
        }
        private bool isItemAvaiableAndNotInstalled(ListViewItem anItem)
        {
            //Check the item and determine if present but not installed
            bool Present = false;

            //Check to see if NOT installed but present
            if ((anItem.SubItems[xTabAvilListData.Installed].Text == CSTR_TabNotInstalled) &&
                ((anItem.SubItems[xTabAvilListData.Present].Text == CSTR_TabPresent)))
            {
                Present = true;
            }
            return Present;
        }
        private void switchTabItemSource(ListViewItem theItem)
        {
            //If the tab was set to default
            if (theItem.SubItems[xTabInstallListData.Source].Text == CSTR_SourceDefault)
            {
                //check for valid file (not MatchIndex 99)
                if (theItem.SubItems[xTabInstallListData.MatchIndex].Text != "99")
                {
                    theItem.SubItems[xTabInstallListData.Source].Text = CSTR_SourceFile;
                }
            }
            else//If the tab was set to file
            {
                //Check tab was in Tab Control file
                if (theItem.SubItems[xTabInstallListData.TCFileIndex].Text != "99")
                {
                    theItem.SubItems[xTabInstallListData.Source].Text = CSTR_SourceDefault;
                }
            }
        }
        private void loadData()
        {
            //Reload the files by re-populating the list views
            InitialiseTabLists();
            InitialiseTabControl();
            InitialiseControls(); 
        }
        private string buildTabControlFile()
        {
            List<string> tabFile = new List<string>();
            List<int> tabIndex = new List<int>();
            //For each item in the installed tab list, get the reference file and index
            foreach (ListViewItem anItem in listViewTabControl.Items)
            {
                string filename = "";
                int tabindex = 0;
                int index = Convert.ToInt16(anItem.SubItems[xTabInstallListData.MatchIndex].Text);
                //Determine the require tab item source
                if ((anItem.SubItems[xTabInstallListData.Source].Text == CSTR_SourceDefault) || (index == 99))
                {
                    //If item is set to populate from the original tab control file (leave filename blank, but set index)
                    tabindex = Convert.ToInt16(anItem.SubItems[xTabInstallListData.TCFileIndex].Text);
                    filename = "";
                }
                else
                {
                    //If item is set to populate tab source from File (leave index as 0)
                    tabindex = 0;
                    filename = listViewAvailable.Items[index].SubItems[xTabAvilListData.KeyFile].Text;
                }
                tabFile.Add(filename);
                tabIndex.Add(tabindex);
            }
            string generatedFile = TabFileBuilder.BuildSenseListFile(tabFile, tabIndex, CSTR_GeneratedTabControlFile);
            return generatedFile;
        }
        private void addAllAvailabeAndNotInstalled()
        {
            //Check each item
            foreach (ListViewItem anItem in listViewAvailable.Items)
            {
                //If available but not installed then add to the list
                if (isItemAvaiableAndNotInstalled(anItem))
                {
                    //We can now add the tab to the Tab Control File's List
                    int targetIndex = 0;
                    if (listViewTabControl.Items.Count - 1 >= 0)
                    {
                        targetIndex = listViewTabControl.Items.Count - 1;
                    }
                    int sourceIndex = anItem.Index;
                    addTabToTabControlList(sourceIndex, targetIndex);

                    //Disable the add button
                    buttonItemAdd.Enabled = false;
                    buttonItemAddAll.Enabled = false;
                }
            }
        }
        private void updateTabControlFile()
        {
            //Disable Button
            buttonTCFUpdate.Enabled = false;

            //Disable Sense
            SenseControl.StopManila();

            //Update file
            replaceTabControlFile();

            //Re-enable Sense
            SenseControl.FullResetManila();
        }
        private void autorunFinish(string argument)
        {
            //Indicate autorun
            if (MessageBox.Show("AutoRun: " + argument, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                //Generate the tab control file
                string generatedFile = buildTabControlFile();
                //update the tab control file
                updateTabControlFile();
                //Reset PPC
                //Check before doing this...
                if (MessageBox.Show("Sense has been updated.  Wait to see if sense starts correctly, if not press OK to perform a soft-reset (device will be restarted, any unsaved data will be lost.)", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    SenseControl.ResetPocketPC();
                }
                //Close!
                Close();
            }

        }
        #endregion
    }
}